package com.ydlclass.loadbalancer.SelectorImpl;

import com.ydlclass.exceptions.CreatLoadBalanceException;
import com.ydlclass.loadbalancer.Selector;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 负载均衡轮询算法
 * @Author duWenJian
 * @Date 2024/2/25 20:07
 * @Version 1.0
 */
@Slf4j
public class RoundRobinSelector implements Selector {

    public List<InetSocketAddress> addresses;
    // 游标位
    public AtomicInteger index;

    public RoundRobinSelector(List<InetSocketAddress> list) {
        this.addresses = list;
        index = new AtomicInteger(0);
    }

    @Override
    public InetSocketAddress getNext() {
        // 轮询的算法
        if (addresses == null || addresses.size() == 0){
            log.error("进行负载均衡选取节点时,服务列表为空");
            throw new CreatLoadBalanceException();
        }
        InetSocketAddress address = addresses.get(index.get());
        if (index.get() == addresses.size() - 1){
            index.set(0);
        } else {
            // 游标后移
            index.incrementAndGet();
        }

        return address;
    }
}
